import pydirectinput as pdi
import pyautogui as pyg
import pygetwindow as gw
import keyboard
import time 
import os

pause = True
ACTION_NAME = "深渊"

DNF_WD = gw.getWindowsWithTitle("Dungeon & Fighter")[0]
DNF_REGION=(DNF_WD.left,DNF_WD.top,DNF_WD.left + DNF_WD.width +50, DNF_WD.top+DNF_WD.height+50)
INIT_WIDTH=800
INIT_HEIGHT=600

def get_image_path(image_name:str):
    return os.path.join(os.path.join(os.path.dirname(__file__),"image"),image_name)

def compute_position(x_offset,y_offset):
    y= DNF_WD.top+(INIT_HEIGHT/2+y_offset)*(DNF_WD.height/INIT_HEIGHT)
    x= DNF_WD.left+(INIT_WIDTH/2+x_offset)*(DNF_WD.width/INIT_WIDTH)
    return x, y

def pause_function():
    global pause 
    pause =  True
    print(f"暂停{ACTION_NAME}")
def start():
    global pause 
    pause =  False
    print(f"开始{ACTION_NAME}")
def move():
    pyg.keyDown("left")

# 定义一个函数来模拟长按右键
def hold_key(duration,key):
    try:
        # 按下右方向键
        pdi.keyDown(key)
        # 等待指定的时间
        time.sleep(duration)
    finally:
        # 释放右方向键
        pdi.keyUp(key)
def running(duration,key):
    try:
        # 按下右方向键
        pdi.press(key)
        pdi.keyDown(key)
        # 等待指定的时间
        time.sleep(duration)
    finally:
        # 释放右方向键
        pdi.keyUp(key)
# 识图封装 300找图,，点一次，相似度0.9，像素步长5,不灰度
def find_img(path, count=10,  confidence=0.95, region=DNF_REGION, grayscale=False, step=5):
    if not os.path.exists(path):
        print(f"文件 {path.split('/')[-1]} 不存在")
        raise FileNotFoundError(f"请输入存在的图片位置{path}")
    attempts = 1
    while attempts < count+1:
        start_time = time.time()
        point = pyg.locateCenterOnScreen(
            path,minSearchTime=0.1, confidence=confidence, region=region, grayscale=grayscale, step=step)
        try:
            end_time = time.time()
            print(f"第{attempts}次 {path.split('/')[-1]} 识别成功 无点击耗时{end_time-start_time:.3f}，region:{region}")
            return True
        except pyg.ImageNotFoundException:
            not_find_time = time.time()
            #print(f"第{attempts}次 {path.split('/')[-1]} 识别失败 耗时{not_find_time-start_time:.3f}，region:{region}")
        attempts += 1
    if attempts >= count:
        pass
        #print("未发现图片")
    return False

def into_xb():
    # 进图
    global  pause
    print(f"开始进入{ACTION_NAME}")
    hold_key(2,"right")
    time.sleep(1)
    pdi.press("f11")
    xb_unselect=get_image_path("xb-unselect.png")
    xb_select_pt = get_image_path("xb-select-pt.png")
    xb_select_dy = get_image_path("xb-select-dy.png")
    if find_img(xb_unselect, region=DNF_REGION):
        pdi.press("up")
        print("切换到西部地图")
    if find_img(xb_select_pt, region=DNF_REGION):
        print("当前为西部普通深渊")
        pdi.press("right")
        pdi.press("right")
        pdi.press("right")
        pdi.press("right")
        if find_img(xb_select_dy, region=DNF_REGION):
            print("已经选择西部地狱模式")
            #pdi.press("space")
    else :
        print("未发现西部图片")
        pause = True
    time.sleep(2.5)

def house_wrap(name,into_image_name, end_image_name, clean_fun=None ,is_sy=False, sy_fun=None,
               again_clean=None,out_house_fun=None):
    print(f"开始第{name}个房间")
    global pause
    retry=0
    max_retry=50
    into_image= get_image_path(into_image_name)
    end_image= get_image_path(end_image_name)
    while not find_img(into_image, region=DNF_REGION) or retry > max_retry:
        time.sleep(0.2)
        retry += 1
    if retry > max_retry:
        print("进入房间失败{name},10s内仍未进入请查看")
        pause = True
    else:
        clean_fun()
        if is_sy:
            sy_fun()
    for i in range(0,2):
        if find_img(end_image, region=DNF_REGION):
            print("怪物清理完成")
            out_house_fun()
        else :
            again_clean()
    if not find_img(end_image, region=DNF_REGION):
        print("怪物未清理结束，请检查程序并调整")
        pause = True



def shenyuan():
    global pause
    cnt = 1
    while True: 
        if pause:
            time.sleep(1)
            cnt=1
        else:
            if cnt <= 1:
                print("开始深渊")
                into_xb()

            if not pause :
                time.sleep(10)
                pdi.press("esc")
                time.sleep(2)
                pdi.press("f10")
                time.sleep(10)
            if cnt>13:
                #回城吃疲劳  
                if not pause :
                    time.sleep(10)
                    pdi.press("F12")
                    time.sleep(5)
                    pdi.press("3")
                    #into_shenyuan()
            cnt=cnt+1
"""
if __name__ == '__main__':
    keyboard.add_hotkey("ctrl+f5",start)
    keyboard.add_hotkey("ctrl+f6",pause_function)
    print(f"1,请按ctrl+f5开始 ，ctrl+f6停止{ACTION_NAME}")
    shenyuan()
"""
        
